<template>
  <el-dialog title="新增" v-model="dialogVisible" width="700px" append-to-body @close="commEvent.onClose">
    <div class="stop-plan-form">
      <!-- 停机时间 -->
      <div class="time-section">
        <span class="time-label">停机时间：</span>
        <el-date-picker
          v-model="formData.stopTime"
          type="date"
          placeholder="年/月/日"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </div>

      <!-- 产线选择穿梭框 -->
      <div class="transfer-section">
        <div class="transfer-container">
          <!-- 待选择 -->
          <div class="transfer-panel">
            <div class="panel-header">待选择</div>
            <div class="panel-content">
              <div class="select-all">
                <el-checkbox
                  v-model="selectAllLeft"
                  :indeterminate="isIndeterminateLeft"
                  @change="(val: any) => commEvent.handleSelectAllLeft(!!val)"
                >
                  全选
                </el-checkbox>
              </div>
              <div class="tree-content">
                <div v-for="factory in leftFactoryList" :key="factory.id" class="factory-item">
                  <div class="factory-header">
                    <el-checkbox
                      v-model="factory.checked"
                      :indeterminate="factory.indeterminate"
                      @change="(val: any) => commEvent.handleFactoryChange(factory)"
                    >
                      {{ factory.name }}
                    </el-checkbox>
                    <el-icon class="expand-icon" @click="factory.expanded = !factory.expanded">
                      <ArrowRight v-if="!factory.expanded" />
                      <ArrowDown v-else />
                    </el-icon>
                  </div>
                  <div v-show="factory.expanded" class="departments-list">
                    <div v-for="department in factory.departments" :key="department.id" class="department-item">
                      <div class="department-header">
                        <el-checkbox
                          v-model="department.checked"
                          :indeterminate="department.indeterminate"
                          @change="commEvent.handleDepartmentChange(department)"
                        >
                          {{ department.name }}
                        </el-checkbox>
                        <el-icon class="expand-icon" @click="department.expanded = !department.expanded">
                          <ArrowRight v-if="!department.expanded" />
                          <ArrowDown v-else />
                        </el-icon>
                      </div>
                      <div v-show="department.expanded" class="lines-list">
                        <div
                          v-for="line in department.lines"
                          :key="line.id"
                          class="line-item"
                          v-show="!isLineInRight(line.factoryId, line.departmentId, line.id)"
                        >
                          <el-checkbox
                            v-model="line.checked"
                            :disabled="line.disabled"
                            @change="commEvent.handleLineChange(department)"
                          >
                            {{ line.name }}
                          </el-checkbox>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 中间操作按钮 -->
          <div class="transfer-buttons">
            <el-button size="small" @click="commEvent.moveToRight" :disabled="getSelectedLeftCount === 0" class="transfer-btn">
              <el-icon><ArrowRight /></el-icon>
            </el-button>
            <el-button size="small" @click="commEvent.moveToLeft" :disabled="getSelectedRightCount === 0" class="transfer-btn">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
          </div>

          <!-- 已选择 -->
          <div class="transfer-panel">
            <div class="panel-header">已选择</div>
            <div class="panel-content">
              <div class="select-all">
                <el-checkbox
                  v-model="selectAllRight"
                  :indeterminate="isIndeterminateRight"
                  @change="(val: any) => commEvent.handleSelectAllRight(!!val)"
                >
                  全选
                </el-checkbox>
              </div>
              <div class="selected-list">
                <div
                  v-for="item in rightList"
                  :key="`${item.factoryId}-${item.departmentId}-${item.lineId}`"
                  class="selected-item"
                >
                  <el-checkbox v-model="item.checked">
                    {{ item.name }}
                  </el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div style="text-align: center">
        <el-button @click="commEvent.onClose">取消</el-button>
        <el-button type="primary" @click="commEvent.onSubmit" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, PropType, watch } from "vue"
import { ElMessage } from "element-plus"
import { ArrowRight, ArrowDown, ArrowLeft } from "@element-plus/icons-vue"
import { EnumProps } from "@/components/ProTable/interface"
import { addStopPlan, getAddedStopLines } from "@/api/modules/stop"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"

// 厂区数据类型（一级）
interface FactoryItem {
  id: number
  name: string
  checked: boolean
  indeterminate: boolean
  expanded: boolean
  departments: DepartmentItem[]
}

// 分厂数据类型（二级）
interface DepartmentItem {
  id: number
  name: string
  checked: boolean
  indeterminate: boolean
  expanded: boolean
  factoryId: number
  lines: LineItem[]
}

// 产线数据类型（三级 - 可穿梭）
interface LineItem {
  id: number
  name: string
  checked: boolean
  factoryId: number
  departmentId: number
  disabled: boolean
}

// 右侧已选择项类型
interface SelectedItem {
  factoryId: number
  departmentId: number
  lineId: number
  name: string
  checked: boolean
}

const props = defineProps({
  modelValue: Boolean,
  factorys: { type: Array as PropType<EnumProps[]>, default: () => [] },
  lines: { type: Array as PropType<EnumProps[]>, default: () => [] }
})

const emit = defineEmits(["update:modelValue", "refresh"])

// 响应式数据
const loading = ref(false)

// 表单数据
const formData = ref({
  stopTime: ""
})

// 左侧待选择数据
const leftFactoryList = ref<FactoryItem[]>([])
// 右侧已选择数据
const rightList = ref<SelectedItem[]>([])

// 全选状态
const selectAllLeft = ref(false)
const selectAllRight = ref(false)
const isIndeterminateLeft = ref(false)
const isIndeterminateRight = ref(false)

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
})

// 检查产线是否已在右侧
const isLineInRight = (factoryId: number, departmentId: number, lineId: number) => {
  return rightList.value.some(
    item => item.factoryId === factoryId && item.departmentId === departmentId && item.lineId === lineId
  )
}

// 获取左侧选中数量
const getSelectedLeftCount = computed(() => {
  let count = 0
  leftFactoryList.value.forEach(factory => {
    factory.departments.forEach(department => {
      department.lines.forEach(line => {
        if (line.checked && !line.disabled && !isLineInRight(line.factoryId, line.departmentId, line.id)) {
          count++
        }
      })
    })
  })
  return count
})

// 获取右侧选中数量
const getSelectedRightCount = computed(() => {
  return rightList.value.filter(item => item.checked).length
})

// 事件处理
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    commEvent.resetData()
    emit("update:modelValue", false)
  },
  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.pid,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },
  // 重置数据
  resetData: () => {
    formData.value.stopTime = ""
    rightList.value = []
    commEvent.initLeftData()
  },

  // 初始化左侧数据
  initLeftData: async () => {
    try {
      // 获取组织架构数据
      const { data: organData } = await organTree()

      // 使用formatMenu格式化数据
      const formattedData = commEvent.formatMenu(organData)

      leftFactoryList.value = formattedData.map((factory: any) => ({
        id: factory.id,
        name: factory.text,
        checked: false,
        indeterminate: false,
        expanded: true,
        departments: (factory.children || []).map((department: any) => ({
          id: department.id,
          name: department.text,
          checked: false,
          indeterminate: false,
          expanded: true,
          factoryId: factory.id,
          lines: (department.children || []).map((line: any) => ({
            id: line.id,
            name: line.text,
            checked: false,
            factoryId: factory.id,
            departmentId: department.id,
            disabled: false
          }))
        }))
      }))

      // 如果有选择停机时间，加载已添加的产线
      if (formData.value.stopTime) {
        await commEvent.loadAddedLines()
      }
    } catch (error) {
      console.error("加载组织数据失败：", error)
      ElMessage.error("加载数据失败")
    }
  },
  // 加载已添加的停机产线
  loadAddedLines: async () => {
    if (!formData.value.stopTime) return

    try {
      const { data: addedLineIds } = await getAddedStopLines(formData.value.stopTime)

      // 设置已添加的产线为禁用状态
      leftFactoryList.value.forEach(factory => {
        factory.departments.forEach(department => {
          department.lines.forEach(line => {
            if (addedLineIds.includes(line.id)) {
              line.disabled = true
              line.checked = false
            } else {
              line.disabled = false
            }
          })
        })
      })

      console.log("已添加的产线：", addedLineIds)
    } catch (error) {
      console.error("加载已添加产线失败：", error)
    }
  },

  // 处理厂区选择变化
  handleFactoryChange: (factory: FactoryItem) => {
    factory.departments.forEach(department => {
      department.checked = factory.checked
      department.indeterminate = false
      department.lines.forEach(line => {
        if (!line.disabled) {
          line.checked = factory.checked
        }
      })
    })
    factory.indeterminate = false
    commEvent.updateSelectAllState("left")
  },

  // 处理分厂选择变化
  handleDepartmentChange: (department: DepartmentItem) => {
    department.lines.forEach(line => {
      if (!line.disabled) {
        line.checked = department.checked
      }
    })
    department.indeterminate = false

    // 更新父级厂区状态
    const factory = leftFactoryList.value.find(f => f.id === department.factoryId)
    if (factory) {
      commEvent.updateFactoryState(factory)
    }
    commEvent.updateSelectAllState("left")
  },

  // 处理产线选择变化
  handleLineChange: (department: DepartmentItem) => {
    const enabledLines = department.lines.filter(line => !line.disabled)
    const checkedLines = department.lines.filter(line => line.checked && !line.disabled)
    department.checked = enabledLines.length > 0 && checkedLines.length === enabledLines.length
    department.indeterminate = checkedLines.length > 0 && checkedLines.length < enabledLines.length

    // 更新父级厂区状态
    const factory = leftFactoryList.value.find(f => f.id === department.factoryId)
    if (factory) {
      commEvent.updateFactoryState(factory)
    }
    commEvent.updateSelectAllState("left")
  },

  // 更新厂区状态
  updateFactoryState: (factory: FactoryItem) => {
    const enabledDepartments = factory.departments.filter(dept => dept.lines.some(line => !line.disabled))
    const checkedDepartments = factory.departments.filter(dept => dept.checked)
    const indeterminateDepartments = factory.departments.filter(dept => dept.indeterminate)

    factory.checked = enabledDepartments.length > 0 && checkedDepartments.length === enabledDepartments.length
    factory.indeterminate =
      (checkedDepartments.length > 0 && checkedDepartments.length < enabledDepartments.length) ||
      indeterminateDepartments.length > 0
  },

  // 处理左侧全选
  handleSelectAllLeft: (checked: boolean) => {
    leftFactoryList.value.forEach(factory => {
      factory.checked = checked
      factory.indeterminate = false
      factory.departments.forEach(department => {
        department.checked = checked
        department.indeterminate = false
        department.lines.forEach(line => {
          if (!line.disabled) {
            line.checked = checked
          }
        })
      })
    })
    isIndeterminateLeft.value = false
  },

  // 处理右侧全选
  handleSelectAllRight: (checked: boolean) => {
    rightList.value.forEach(item => {
      item.checked = checked
    })
    isIndeterminateRight.value = false
  },

  // 更新全选状态
  updateSelectAllState: (side: "left" | "right") => {
    if (side === "left") {
      let totalLines = 0
      let checkedLines = 0

      leftFactoryList.value.forEach(factory => {
        factory.departments.forEach(department => {
          department.lines.forEach(line => {
            if (!line.disabled) {
              totalLines++
              if (line.checked) {
                checkedLines++
              }
            }
          })
        })
      })

      selectAllLeft.value = totalLines > 0 && checkedLines === totalLines
      isIndeterminateLeft.value = checkedLines > 0 && checkedLines < totalLines
    } else {
      const checkedCount = rightList.value.filter(item => item.checked).length
      selectAllRight.value = rightList.value.length > 0 && checkedCount === rightList.value.length
      isIndeterminateRight.value = checkedCount > 0 && checkedCount < rightList.value.length
    }
  },

  // 移到右侧
  moveToRight: () => {
    leftFactoryList.value.forEach(factory => {
      factory.departments.forEach(department => {
        const selectedLines = department.lines.filter(
          line => line.checked && !line.disabled && !isLineInRight(line.factoryId, line.departmentId, line.id)
        )
        selectedLines.forEach(line => {
          rightList.value.push({
            factoryId: line.factoryId,
            departmentId: line.departmentId,
            lineId: line.id,
            name: `${factory.name}-${department.name}-${line.name}`,
            checked: false
          })
        })
        // 重置左侧选中状态（只重置未禁用的）
        department.lines.forEach(line => {
          if (!line.disabled) {
            line.checked = false
          }
        })
        department.checked = false
        department.indeterminate = false
      })
      factory.checked = false
      factory.indeterminate = false
    })
    commEvent.updateSelectAllState("left")
    commEvent.updateSelectAllState("right")
  },

  // 移到左侧
  moveToLeft: () => {
    const selectedItems = rightList.value.filter(item => item.checked)

    // 从右侧移除选中的项目
    selectedItems.forEach(item => {
      const index = rightList.value.findIndex(
        r => r.factoryId === item.factoryId && r.departmentId === item.departmentId && r.lineId === item.lineId
      )
      if (index > -1) {
        rightList.value.splice(index, 1)
      }
    })

    commEvent.updateSelectAllState("right")
  },

  // 提交数据
  onSubmit: async () => {
    if (!formData.value.stopTime) {
      ElMessage.warning("请选择停机时间")
      return
    }

    if (rightList.value.length === 0) {
      ElMessage.warning("请选择要停机的产线")
      return
    }

    try {
      loading.value = true

      // 准备提交数据
      const submitData = {
        lineIds: rightList.value.map(item => item.lineId),
        stopDay: formData.value.stopTime,
        remark: ""
      }

      console.log("提交停机计划数据：", submitData)

      // 调用新增停机计划的API
      const result = await addStopPlan(submitData)

      if (result.code === "200") {
        ElMessage.success("新增成功")
        emit("refresh")
        commEvent.onClose()
      } else {
        ElMessage.error("新增失败")
      }
    } catch (error) {
      console.error("新增停机计划失败：", error)
      ElMessage.error("新增失败，请重试")
    } finally {
      loading.value = false
    }
  }
}

// 监听弹窗打开
watch(
  () => props.modelValue,
  val => {
    if (val) {
      commEvent.initLeftData()
    }
  }
)

// 监听停机时间变化
watch(
  () => formData.value.stopTime,
  async newTime => {
    if (newTime && leftFactoryList.value.length > 0) {
      await commEvent.loadAddedLines()
    }
  }
)
</script>

<style lang="scss" scoped>
.stop-plan-form {
  .time-section {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .time-label {
      font-size: 14px;
      color: #606266;
      margin-right: 10px;
    }
  }

  .transfer-section {
    .transfer-container {
      display: flex;
      gap: 20px;
      align-items: flex-start;

      .transfer-panel {
        flex: 1;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        background: #fff;

        .panel-header {
          background: #f5f7fa;
          padding: 10px 15px;
          border-bottom: 1px solid #dcdfe6;
          font-size: 14px;
          font-weight: 500;
        }

        .panel-content {
          height: 300px;
          overflow-y: auto;
          padding: 10px;

          .select-all {
            padding: 5px 0;
            border-bottom: 1px solid #ebeef5;
            margin-bottom: 10px;
          }

          .tree-content {
            .factory-item {
              margin-bottom: 8px;

              .factory-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 5px 0;
                cursor: pointer;

                .expand-icon {
                  cursor: pointer;
                  color: #909399;

                  &:hover {
                    color: #409eff;
                  }
                }
              }

              .departments-list {
                margin-left: 20px;
                margin-top: 5px;

                .department-item {
                  margin-bottom: 8px;

                  .department-header {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 3px 0;
                    cursor: pointer;

                    .expand-icon {
                      cursor: pointer;
                      color: #909399;

                      &:hover {
                        color: #409eff;
                      }
                    }
                  }

                  .lines-list {
                    margin-left: 20px;
                    margin-top: 5px;

                    .line-item {
                      padding: 3px 0;
                      font-size: 13px;

                      :deep(.el-checkbox.is-disabled) {
                        .el-checkbox__label {
                          color: #c0c4cc;
                          text-decoration: line-through;
                        }
                      }
                    }
                  }
                }
              }
            }
          }

          .selected-list {
            .selected-item {
              padding: 5px 0;
              border-bottom: 1px solid #f0f0f0;

              &:last-child {
                border-bottom: none;
              }
            }
          }
        }
      }

      .transfer-buttons {
        display: flex;
        flex-direction: column;
        justify-content: center;
        gap: 10px;
        margin: 0 10px;

        .transfer-btn {
          width: 40px;
          height: 32px;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}

:deep(.el-checkbox) {
  .el-checkbox__label {
    font-size: 14px;
    color: #606266;
  }
}

:deep(.el-date-editor) {
  .el-input__wrapper {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
  }
}
</style>
